﻿/*--------------------------------------------------------------------------------
 * Adaptive Intelligence - Foundation Framework Class Library
 * Version 2.00
 * 
 * ZIP Central Directory Class
 * 		Represents and manages the central directory section of a PKZIP file.
 *------------------------------------------------------------------------------*/

/*--------------------------------------------------------------------------------
 * System Imports
 *------------------------------------------------------------------------------*/
using System;
using System.IO;

namespace Adaptive.Foundation.IO.Zip
{
    /// <summary>
    /// Represents and manages the central directory section of a PKZIP file.
    /// </summary>
    /// <remarks>
    /// 
    /// </remarks>
    public sealed class ZipCentralDirectory : AiObjectBase, IStorable
    {
        /*--------------------------------------------------------------------------------
         * Private Member Declarations
         *------------------------------------------------------------------------------*/
        #region Private Member Declarations
        /// <summary>
        /// List of entries in the directory.
        /// </summary>
        private ZipCentralDirectoryEntryCollection _entryList;
        /// <summary>
        /// Digital signature record.
        /// </summary>
        private ZipDigitalSignature _digitalSignature;
        /// <summary>
        /// Last record.
        /// </summary>
        private ZipCentralDirectoryEndRecord _lastRecord;
        #endregion

        /*--------------------------------------------------------------------------------
         * Constructor / Dispose / Destructor Methods
         *------------------------------------------------------------------------------*/
        #region Constructor / Dispose / Destructor Methods
        /// <summary>
        /// Initializes a new instance of the <see cref="ZipCentralDirectory" /> class.
        /// </summary>
        public ZipCentralDirectory()
            : base()
        {
            _entryList = new ZipCentralDirectoryEntryCollection();
            _lastRecord = new ZipCentralDirectoryEndRecord();
        }
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><b>true</b> to release both managed and unmanaged resources;
        /// <b>false</b> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if ((!Disposed) && (disposing))
            {
                Clear();
                if (_entryList != null)
                    _entryList.ClearAndDispose();

                if (_lastRecord != null)
                    _lastRecord.Dispose();

                if (_digitalSignature != null)
                    _digitalSignature.Dispose();
            }

            _lastRecord = null;
            _entryList = null;
            _digitalSignature = null;
            base.Dispose(disposing);
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Public Properties
         *------------------------------------------------------------------------------*/
        #region Public Properties
        /// <summary>
        /// Gets the reference to the list of entries in the directory.
        /// </summary>
        /// <value>The entry list.</value>
        public ZipCentralDirectoryEntryCollection EntryList
        {
            get
            {
                return _entryList;
            }
        }
        /// <summary>
        /// Gets the reference to the digital signature record.
        /// </summary>
        public ZipDigitalSignature DigitalSignature
        {
            get
            {
                return _digitalSignature;
            }
        }
        /// <summary>
        /// Last record.
        /// </summary>
        public ZipCentralDirectoryEndRecord LastRecord
        {
            get
            {
                return _lastRecord;
            }
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Public Methods / Functions
         *------------------------------------------------------------------------------*/
        #region Public Methods / Functions
        /// <summary>
        /// Resets the property values for all items in the instance to their default values, and
        /// clears any internal lists or collections.
        /// </summary>
        public override void Clear()
        {
            if (_entryList != null)
                _entryList.ClearAndDispose();

            if (_digitalSignature != null)
            {
                _digitalSignature.Dispose();
                _digitalSignature = null;
            }

            if (_lastRecord != null)
                _lastRecord.Clear();

            base.Clear();
        }
        /// <summary>
        /// Loads the content for the instance from the specified stream.
        /// </summary>
        /// <param name="reader">An open <see cref="BinaryReader" /> used to read data from the
        /// underlying stream.</param>
        /// <returns>
        /// <b>true</b> if the load operation is successful; otherwise, <b>false</b>.
        /// </returns>
        public bool Load(BinaryReader reader)
    {

		bool returnValue = false;						//Return value.
		int signatureValue = 0;						    //Data element signature.
		ZipCentralDirectoryEntry newEntry = null;		//Zip Directory File Header
		bool endReached = false;				        //End of directory flag.

		//Clear previous contents.
		Clear();

		try
        {
			do
            {
				//Evaluate item by signature. ("Peek" at the data.)
				signatureValue = reader.ReadInt32();
				reader.BaseStream.Seek(-4, SeekOrigin.Current);

				switch((ZipSignatures)signatureValue)
                {
					case ZipSignatures.CentralDirectoryHeader:

						//Read a new entry.
						newEntry = new ZipCentralDirectoryEntry();
						newEntry.Load(reader);
						_entryList.Add(newEntry);
                        break;

					case ZipSignatures.DigitalSignature:

						//Read the digital signature.
						_digitalSignature = new ZipDigitalSignature();
						_digitalSignature.Load(reader);
                        break;

					case ZipSignatures.EndCentralDirectory:

						//Read the end-of-directory record and stop.
						_lastRecord.Load(reader);
						endReached = true;
                        break;

					default:
                        throw new Exception("Invalid file format.");

				}

			} while ((!endReached) && (reader.BaseStream.Position < reader.BaseStream.Length));

            returnValue = true;
        }
		catch(IOException)
        {
        }

        return returnValue;
    }
        /// <summary>
        /// Saves the content for the instance to the specified stream.
        /// </summary>
        /// <param name="writer">An open <see cref="BinaryWriter" /> used to write data to the
        /// underlying stream.</param>
        /// <returns>
        /// <b>true</b> if the save operation is successful; otherwise, <b>false</b>.
        /// </returns>
        public bool Save(BinaryWriter writer)
        {
            bool returnValue = false;
            long startPosition = 0;
            long endPosition = 0;

            startPosition = writer.BaseStream.Position;
            try
            {
                //Write the entries to disk.
                _entryList.MoveFirst();
                while (!(_entryList.Eof))
                {
                    _entryList.Value.Save(writer);
                    _entryList.MoveNext();

                }

                //Write the digital signature, if present.
                if (_digitalSignature != null)
                    _digitalSignature.Save(writer);

                //Write the end-of-directory record.
                endPosition = writer.BaseStream.Position;
                _lastRecord.DirectoryOffset = Convert.ToInt32(startPosition);
                _lastRecord.DirectorySize = Convert.ToInt32(endPosition) - Convert.ToInt32(startPosition);
                _lastRecord.DiskNumber = 0;
                _lastRecord.DiskNumberStart = 0;
                _lastRecord.TotalEntries = Convert.ToInt16(_entryList.Count);
                _lastRecord.TotalEntriesOnDisk = Convert.ToInt16(_entryList.Count);
                _lastRecord.Save(writer);

                writer.Flush();
                returnValue = true;
            }
            catch (IOException)
            {
            }

            return returnValue;
        }
        #endregion
    }
}
